#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# $Id$

__version__     = '0.0.0'
__revision___   = "$Id$"
__author__      = "Kai Kasurinen"
__email__       = "kai.kasurinen@uninea.fi"
__copyright__   = "Copyright 2008, Kai Kasurinen"

import os
import optparse
import logging
import ConfigParser

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor



class YouLoc(DatagramProtocol):

    def datagramReceived(self, data, (host, port)):
        logging.debug("received %r from %s:%d" % (data.splitlines(), host, port))
        self.parseData(data)

    def parseData(self, data):
        # "IMEI 123456789012345\r\n$GPRMC,144858.159,A,6009.0358,N,02453.3223,E,0.00,006.40,191104,,*05\r\nOutCell 38091 LAC 30464 Name SAT-C MCC 510 MNC 1\r\nIn Cell 34747 LAC 2161 Name SONERA MCC 244 MNC 91\r\nLabel Aspicore Ltd\r\n*DE6279AE\r\n"
        data = data.splitlines()
        for i in data:
            if i.startswith('IMEI'):
                pass
            elif i.startswith('$GPRMC'):
                pass
            elif i.startswith('OutCell'):
                pass
            elif i.startswith('InCell'):
                pass
            elif i.startswith('Label'):
                pass
            elif i.startswith('*'):
                pass
            else:
                logging.debug('unknown line: %s' % i)


def main():
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)s %(message)s')

    logging.debug('reading config...')
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('~/.youloc-udp-server.cfg')])

    reactor.listenUDP(9999, YouLoc())
    reactor.run()


if  __name__ == '__main__':
    parser = optparse.OptionParser(version='youloc-udp-server %s' % __version__)
    (options, args) = parser.parse_args()

    main()